<template>
  <div id="app" :style="{height:windowVisualHeight+'px',width:windowVisualWidth+'px'}">
    <Layout v-if="isLogin && pageShow">
      <Header :style="{padding: 0,cursor:'pointer',height: headerHeight+'px',background: '#1C1E26'}"
              class="layout-header-bar r-n-fs-c">
        <div v-if="!isCollapsed" class="r-n-c-c" :class="isCollapsed?'pulse':''" :style="{width:sideWidth + 'px',height: headerHeight + 'px',color:'#ffffff',padding: '0 10px'}">
          <img src="./assets/logo.png" alt="巡线后台管理" style="width: 30px; height: 30px; color:#ffffff">
          <div style="padding-left: 10px; width:100px; font-size: 20px">IL-ADMIN</div>
        </div>
        <div class="r-n-c-c" :style="{width: headerHeight+'px',height: headerHeight+'px',color:'#ffffff'}">
          <Icon @click.native="collapsedSide" :class="rotateIcon" class="iconfont icon-caidan3"
                :style="{margin: '0 20px',fontSize: '33px!important',color:'#2d8cf0'}" size="24"></Icon>
        </div>
        <div class="item-edr-fill r-n-fe-c">
          <div class="item-edr-fill r-n-fs-c" :style="{height: headerHeight + 'px'}">
            <div class="breadcrumb-item-main r-n-c-c" >
              <router-link to="/admin/dashboard" :style="{color: menuDashboardColor}">主控台</router-link>
            </div>
            <div class="breadcrumb-item r-n-c-c" v-for="item in breadcrumbRouteMap"
                 :key="item.name"
                 :name="item.name">
              <router-link style="" :to="item.to" :style="{color: item.color}">{{ item.span }}</router-link>
              <Icon class="breadcrumb-item-icon" @click="closeBreadcrumbMenu(item)" type="md-close" size="16"></Icon>
            </div>
          </div>
          <div class="r-n-c-c" :style="{height: headerHeight + 'px'}">
            <div @click="fullScreen(isFullScreen)" style="width: 40px;height:52px;line-height: 52px;font-size:20px!important;text-align:center;" class="iconfont icon-quanping1"></div>
            <!--<Badge :count="2">
              <div style="width: 40px;height:28px;line-height: 28px;font-size:20px!important;text-align:center;" class="iconfont icon-xiaoxi"></div>
            </Badge>-->
          </div>
          <div class="r-n-c-c" :style="{height: headerHeight + 'px',padding: '0 10px'}">
            <img :src="userInfo.avatarUrl" alt="头像" style="width: 25px; height: 25px;">
            <div style="height:52px;line-height: 52px;padding-left:5px;font-size:14px!important;text-align:center;display: inline-block">
              {{ userInfo.nickName }}</div>
          </div>
          <Button type="primary" class="r-n-c-c" shape="circle" icon="md-log-out" style="margin-right: 15px;"
                  @click="logout" title="退出登录"></Button>
        </div>
      </Header>
      <Layout>
        <Sider ref="side1" :width="sideWidth+'px'" hide-trigger collapsible :collapsed-width="52" v-model="isCollapsed">
          <Menu @on-select="selectMenu" :active-name="activeName" :style="{height:contentHeight+'px'}" theme="dark"
                width="auto"
                :class="menuitemClasses">
            <MenuItem class="r-n-fs-c" style="padding-left: 10px" v-for="item in routeMap" :key="item.name"
                      :name="item.name" :to="item.to">
              <div class="r-n-c-c" style="width: 32px;height:24px;text-align:center;">
                <div style="width: 32px;height:16px;text-align:center;display: inline-block" class="iconfont" :class="item.icon"></div>
<!--                <Icon style="width: 24px;height:24px;display: flex" :type="item.icon" size="20"/>-->
              </div>
              <span>{{ item.span }}</span>
            </MenuItem>
          </Menu>
        </Sider>
        <Layout>
          <Content :style="{margin: '15px',height: contentHeight + 'px',background:'#FFFFFF'}">
            <router-view/>
          </Content>
        </Layout>
      </Layout>
    </Layout>
    <Login v-if="!isLogin && pageShow"/>
    <div v-if="!pageShow" class="r-n-c-c" :style="{height:windowVisualHeight+'px',width:windowVisualWidth+'px'}" style="color: #FFDDDD;font-size: 24px">服务器连接中...</div>
    <div id="image-show-outer" class="r-n-c-c" v-if="isImageWindowShow">
      <div id="image-show-content" class="r-n-c-c">
        <div @click="closeImageWindow" class="r-n-c-c iconfont icon-guanbi1" :style="{left: windowVisualWidth/2-18 + 'px'}" title="关闭大图"></div>
        <img :style="{maxHeight: contentHeight+ 'px',maxWidth: contentWidth+'px' }" :src="imageWindowUrl" alt="">
      </div>
    </div>
  </div>
</template>

<script>
import Login from './components/Login.vue'


import {mapState, mapGetters} from "vuex"
import axios from "axios";
import {createWebSocket,closeWebSocket} from "@/global/webSocket";
import {webSocketUrl,Request} from "@/global/config";
import store from "@/store";

export default {
  name: 'App',
  components: {
    Login
  },
  data() {
    return {
      activeName: "1",
      isCollapsed: true,
      isFullScreen: false,
      currentRoute: {
        name: "1",
        to: "/admin/dashboard",
        icon: "icon-caidanzhukongtai",
        span: "主控台",
        color: "#808695"
      },
      breadcrumbRouteMap: [],
      routeMap: [
        {
          name: "1",
          to: "/admin/dashboard",
          icon: "icon-caidanzhukongtai",
          span: "主控台",
          color: "#808695"
        },
        {
          name: "2",
          to: "/admin/project",
          icon: "icon-xiangmuguanli",
          span: "项目管理",
          color: "#808695"
        },
        {
          name: "3",
          to: "/admin/user",
          icon: "icon-yonghuguanli",
          span: "用户管理",
          color: "#808695"
        },
        {
          name: "4",
          to: "/admin/pipeline",
          icon: "icon-guanxian",
          span: "管线管理",
          color: "#808695"
        },
        {
          name: "5",
          to: "/admin/flyTask",
          icon: "icon-lishirenwu",
          span: "飞行任务",
          color: "#808695"
        },
        {
          name: "6",
          to: "/admin/danger",
          icon: "icon-xianqingxinxi",
          span: "险情信息",
          color: "#808695"
        },
        {
          name: "7",
          to: "/admin/infrastructure",
          icon: "icon-jichusheshi",
          span: "基础设施",
          color: "#808695"
        },
        {
          name: "8",
          to: "/admin/infrastructureType",
          icon: "icon-sheshileixing",
          span: "类型管理",
          color: "#808695"
        },
        {
          name: "9",
          to: "/admin/orthographicImage",
          icon: "icon-zhengsheyingxiang",
          span: "正射影像",
          color: "#808695"
        },
        {
          name: "10",
          to: "/admin/client",
          icon: "icon-kehuduan",
          span: "客户端",
          color: "#808695"
        }
      ]
    }
  },
  watch: {
    isCollapsed:function (value){
      this.$store.state.realSideWidth = value ? 52 : 200;
    },
    '$route.path': function (path) {
      this.routeMap.forEach(route => {
        if (path === route.to) {
          this.currentRoute = route;
          this.activeName = route.name;
          this.breadcrumbRouteMap.map(route0 => {
            if (route0.to === path) {
              route0.color = '#2d8cf0'
            } else {
              if (route0.color === '#2d8cf0') {
                route0.color = '#808695'
              }
            }
          })
          localStorage.setItem("breadcrumbRouteMap",JSON.stringify(this.breadcrumbRouteMap));
        }
      });

    }
  },
  computed: {
    ...mapState(["userInfo","url","seq", "windowVisualHeight", "windowVisualWidth", "sideWidth","realSideWidth", "headerHeight", "footerHeight", "isLogin","isImageWindowShow","imageWindowUrl","pageShow"]),
    ...mapGetters(["contentHeight","contentWidth"]),
    rotateIcon() {
      return [
        'menu-icon',
        this.isCollapsed ? 'rotate-icon' : ''
      ];
    },
    menuDashboardColor() {
      return this.currentRoute.name === '1' ? '#2d8cf0' : '#808695'
    },
    menuitemClasses() {
      return [
        'menu-item',
        this.isCollapsed ? 'collapsed-menu' : ''
      ]
    }
  },
  created: function () {
    this.setWindowSize();
    window.onresize = () => {
      this.setWindowSize();
    }
    if (localStorage.getItem("seq") === null){
      localStorage.setItem("seq",0)
    }else {
      let seqNumber = Number.parseInt(localStorage.getItem("seq"));
      seqNumber++;
      this.$store.state.seq = seqNumber;
      localStorage.setItem("seq",seqNumber);
    }
  },
  mounted: function () {
    let self = this;
    let startLocation = this.$router.history._startLocation;
    let breadcrumbRouteMapStorage = JSON.parse(localStorage.getItem('breadcrumbRouteMap'));
    if (breadcrumbRouteMapStorage !== null){
      self.breadcrumbRouteMap = breadcrumbRouteMapStorage;
    }
    self.routeMap.forEach(((route) => {
      if (startLocation === route.to) {
        this.activeName = route.name;
        this.currentRoute = route;
      }
    }));
    axios.post(self.url.user_state).then(function (response) {
      if (response.data.state === 200) {
        self.userInfo.avatarUrl = localStorage.getItem("avatarUrl");
        self.userInfo.nickName = localStorage.getItem("nickName");
        let resourceHost0 = localStorage.getItem("resourceHost");
        if (resourceHost0 !== null){
          self.$store.state.resourceHost = resourceHost0;
        }
        if (startLocation === '/'){
          self.$router.push('/admin/dashboard');
        }
        self.$Message.success("已登录");
        createWebSocket();
        Request.selectProjectList().then((projectRsp)=>{
          self.$store.state.projectList = projectRsp.data.content.records;
          for (let project of projectRsp.data.content.records) {
            self.$store.state.projectMap.set(project['id'],project['projectName']);
            self.$store.state.projectDetailsMap.set(project['id'],project);
          }
          self.$store.state.isLogin = true;
          self.$store.state.pageShow = true;
        })
      } else {
        self.$store.state.isLogin = false;
        self.$store.state.pageShow = true;
      }
    })
    //setTimeout(()=>{this.test();},2000)
  },
  methods: {
    test(){
      let self = this;
      let successCount = 0;
      let requestTimes = 1000;
      let currentTime = 0;
      let startTime = self.moment.now();
      callSelf();
      function callSelf(){
        let startTime0 = self.moment.now();
        axios.get(self.url.pipeline_list_db).then(function (response) {
          let endTime0 = self.moment.now();
          let {state,message} = response.data
          currentTime ++;
          console.log("["+currentTime+ "] Time:" + (endTime0-startTime0)/1000 + " "+message);
          if (state === 200){
            successCount ++;
            if (currentTime === requestTimes){
              let endTime = self.moment.now();
              console.log("请求总计："+requestTimes+"次,成功"+successCount+"次,并发时长:"+(endTime-startTime)/1000+"秒")
            }else {
              callSelf()
            }
          }
        }).catch(function () {
          self.isLoading = false;
        });
      }
    },
    closeImageWindow:function (e) {
      this.$store.state.isImageWindowShow = false;
      this.$store.state.imageWindowUrl = null;
    },
    fullScreen(isFullScreen){
      if (isFullScreen){
        let el = document;
        let cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen;

        //typeof cfs != "undefined" && cfs
        if (cfs) {
          cfs.call(el);
        }
        else if (typeof window.ActiveXObject !== "undefined") {
          //for IE，这里和fullScreen相同，模拟按下F11键退出全屏
          let script = new ActiveXObject("WScript.Shell");
          if (script != null) {
            script.SendKeys("{F11}");
          }
        }
        this.isFullScreen = false;
      } else {
        let el = document.documentElement;
        let rfs = el.requestFullscreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen;

        //typeof rfs != "undefined" && rfs
        if (rfs) {
          rfs.call(el);
        }
        else if (typeof window.ActiveXObject !== "undefined") {
          //for IE，这里其实就是模拟了按下键盘的F11，使浏览器全屏
          let script = new ActiveXObject("WScript.Shell");
          if (script != null) {
            script.SendKeys("{F11}");
          }
        }
        this.isFullScreen = true;
      }
    },
    closeBreadcrumbMenu(route){
      let self = this;
      let deleteIndex = self.breadcrumbRouteMap.indexOf(route);
      let spliceRoute = self.breadcrumbRouteMap.splice(deleteIndex,1);
      localStorage.setItem('breadcrumbRouteMap',JSON.stringify(self.breadcrumbRouteMap));
      if (spliceRoute[0].name === self.currentRoute.name){
        let length = self.breadcrumbRouteMap.length;
        if (length === 0){
          this.$router.push(self.routeMap[0].to);
          return;
        }
        if (length === 1){
          this.$router.push(self.breadcrumbRouteMap[0].to);
          return;
        }
        if (deleteIndex === 0 && length > 1){
          this.$router.push(self.breadcrumbRouteMap[0].to);
          return;
        }
        if (deleteIndex === length && length > 1){
          this.$router.push(self.breadcrumbRouteMap[deleteIndex-1].to);
        }else{
          this.$router.push(self.breadcrumbRouteMap[deleteIndex].to);
        }
      }
    },
    selectMenu(name) {
      let self = this;
      this.routeMap.forEach((route) => {
        if (name === route.name) {
          this.currentRoute = route;
          let isInBreadcrumbRouteMap = false;
          if (route.name === '1') {
            isInBreadcrumbRouteMap = true;
          }
          self.breadcrumbRouteMap.map(route0 => {
            if (route0.name === route.name) {
              route0.color = '#2d8cf0'
              self.activeName = route.name;
              isInBreadcrumbRouteMap = true;
            } else {
              if (route0.color === '#2d8cf0') {
                route0.color = '#808695'
              }
            }
          })
          if (!isInBreadcrumbRouteMap) {
            route.color = '#2d8cf0';
            //添加属性，绑定Vue数据渲染 Setter Getter
            route = Object.assign({}, route);
            if (self.breadcrumbRouteMap.length === 6){
              self.breadcrumbRouteMap.shift();
            }
            self.breadcrumbRouteMap.push(route);
            localStorage.setItem('breadcrumbRouteMap',JSON.stringify(self.breadcrumbRouteMap));
          }
        }
      })
    },
    logout() {
      let self = this;
      self.$Spin.show();
      axios.post(self.url.user_logout).then(function (response) {
        if (response.data.state === 200) {
          window.localStorage.removeItem("u-token");
          window.localStorage.removeItem("u-uid");
          window.localStorage.removeItem("u-projectId");
          axios.defaults.headers.common["u-token"] = null;
          axios.defaults.headers.common["u-uid"] = null;
          axios.defaults.headers.common["u-projectId"] = null;
          self.$store.state.isLogin = false;
          closeWebSocket();
          self.$Message.info(response.data.message);
        } else {
          self.$Message.error(response.data.message);
        }
        self.$Spin.hide();
      })
    },
    setWindowSize() {
      this.$store.state.windowVisualHeight = window.innerHeight <= 500 ? 500 : window.innerHeight;
      this.$store.state.windowVisualWidth = window.innerWidth <= 1200 ? 1200 : window.innerWidth;
    },
    collapsedSide() {
      this.$refs.side1.toggleCollapse();
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  position: relative;
  background: #2e2f30;
  /*border-radius: 4px;*/
  overflow: auto;
  height: 100vh;
}
.iconfont{
  font-size: 14px!important;
}
#image-show-outer{
  height: 100vh;
  width: 100%;
  background: #000000E0;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10000;
}

#image-show-content{
  height: 80vh;
}
.icon-guanbi1{
  height: 36px;
  width: 36px;
  position: absolute;
  right: -15px;
  top: 10px;
  font-size: 36px!important;
  color: #e3e3e3;
  cursor: pointer;
  border-radius: 50%;
}
.icon-guanbi1:hover{
  color: #FFFFFF;
  border: solid 1px #FFFFFF;
}
.ivu-badge-count {
  height: 14px!important;
  line-height: 12px!important;
  padding: 0 4px!important;
  top: -4px!important;
  right: 10px!important;
}
.layout-footer-center {
  text-align: center;
}

.layout-header-bar {
  background: #fff;
  /*box-shadow: 0 1px 1px rgba(0, 0, 0, .1);*/
}

.layout-logo-left {
  width: 90%;
  height: 30px;
  background: #5b6270;
  border-radius: 3px;
  margin: 15px auto;
}

.menu-icon {
  transition: all .3s;
}

.rotate-icon {
  transform: rotate(-90deg);
}

.menu-item {
  line-height: 1.0;
}

.menu-item span {
  display: inline-block;
  overflow: hidden;
  width: 120px;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: bottom;
  transition: width .2s ease .2s;
  font-size: 15px;
  line-height: 22px;
}

.ivu-menu-item span {

}

.menu-item i {
  transform: translateX(0px);
  transition: font-size .2s ease, transform .2s ease;
  vertical-align: middle;
  font-size: 20px;
  line-height: 24px;
}

.collapsed-menu span {
  width: 0px;
  font-size: 18px;
  transition: width .2s ease;
}

.collapsed-menu i {
  transform: translateX(5px);
  transition: font-size .2s ease .2s, transform .2s ease .2s;
  vertical-align: middle;
  font-size: 24px;
  line-height: 1.0;
}

input:-webkit-autofill {
  -webkit-box-shadow: 0 0 0 1000px #002b43 inset !important;
  -webkit-text-fill-color: #fff !important;
}

.breadcrumb-item-main {
  height: 32px;
  width: auto;
  background: #fff;
  border-radius: 3px;
  border: none;
  color: #808695;
  text-align: center;
  cursor: pointer;
  padding: 5px 16px;
}

.breadcrumb-item-main a, .breadcrumb-item a {
  color: #808695;
}

a:active, a:hover {
  outline: 0;
  text-decoration: none;
}

a:hover {
  color: #515a6e;
}

.breadcrumb-item-main:hover, .breadcrumb-item:hover a {
  color: #515a6e;
}

.breadcrumb-item-main:hover, .breadcrumb-item:hover {
  color: #515a6e;
}

.breadcrumb-item {
  height: 32px;
  width: auto;
  background: #fff;
  border-radius: 3px;
  border: none;
  margin-left: 6px;
  color: #808695;
  text-align: center;
  cursor: pointer;
  padding: 5px 16px;
}

.breadcrumb-item-icon {
  width: 16px;
  height: 22px;
  line-height: 22px !important;
  margin-left: 6px;
}
</style>
